<!--
 * @Author: underMoonzs 1994186472@qq.com
 * @Date: 2025-10-06 11:52:01
 * @LastEditors: underMoonzs 1994186472@qq.com
 * @LastEditTime: 2025-10-07 15:17:47
 * @FilePath: \environment-map-app\src\components\EnvironmentMap.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div ref="mapContainer" class="map-container"></div>
</template>

<script setup>
import { onMounted, ref, inject, onUnmounted,defineEmits } from 'vue'
import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import { XYZ } from 'ol/source';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import { defaults as defaultInteractions } from 'ol/interaction';
import { createPointLayer } from '../main/layerLoader'
const map = ref(null)
const mapContainer = ref(null)
// 使用 Vite 环境变量
const tiandituToken = ref(import.meta.env.VITE_APP_TIANDITU_TOKEN || '3d9e801ed2c10bc2e6eba8037e53817b')
const loadedLayers = ref({});

const emitter = inject('emitter')
import { getData } from '../main/getData'

const emit = defineEmits(['layer-click'])

// 检测是否为触摸设备
const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;

const registerMapClick = () => {
  // 根据设备类型选择合适的事件
  const clickEvent = isTouchDevice ? 'singleclick' : 'singleclick';
  
  map.value.on(clickEvent, (evt) => {
    const features = [];
    map.value
      .forEachFeatureAtPixel(evt.pixel, (feature) => {
        features.push(feature);
      });

    // 如果找到了要素，则可以进一步处理
    if (features.length > 0) {
      // 处理获取到的要素
      const feature = features[0];
      // console.log('点击到的要素:', feature);
      // 获取要素属性
      const featureData = feature.getProperties();
      // 获取图层信息
      const layerId = feature ? feature.get('layerId') : '';
      console.log('图层ID:', layerId);
       emit('layer-click', layerId, featureData.id, featureData)
    }
  });
}

const initMap = () => {
  // 根据设备类型调整交互配置
  const interactions = defaultInteractions({
    pinchRotate: false,
    // 在触摸设备上优化拖拽体验
    dragPan: true
  });

  map.value = new Map({
    target: mapContainer.value,
    layers: [
      new TileLayer({
        name: 'tianditu-vec',
        source: new XYZ({
          url: `http://t{0-7}.tianditu.gov.cn/vec_c/wmts?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&LAYER=vec&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${tiandituToken.value}`,
          projection: 'EPSG:4326',
          tileGrid: new WMTSTileGrid({
            origin: [-180, 90],
            resolutions: [1.40625, 0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 0.0006866455078125, 0.00034332275390625, 0.000171661376953125, 0.0000858306884765625],
            matrixIds: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']
          })
        })
      }),
      new TileLayer({
        name: 'tianditu-cva',
        source: new XYZ({
          url: `http://t{0-7}.tianditu.gov.cn/cva_c/wmts?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetTile&LAYER=cva&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${tiandituToken.value}`,
          projection: 'EPSG:4326',
          tileGrid: new WMTSTileGrid({
            origin: [-180, 90],
            resolutions: [1.40625, 0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 0.0006866455078125, 0.00034332275390625, 0.000171661376953125, 0.0000858306884765625],
            matrixIds: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']
          })
        })
      })
    ],
    view: new View({
      projection: 'EPSG:4326',
      center: [112.930691, 35.791355],
      zoom: 10,
      maxZoom: 18,
      minZoom: 1
    }),
    interactions: interactions,
  });

  registerMapClick()
}

const removeLayer = (layerId) => {
  if (loadedLayers.value[layerId]) {
    map.value.removeLayer(loadedLayers.value[layerId]);
    delete loadedLayers.value[layerId];
  }
}

const addLayerToMap = (newLayer, layerConfig) => {
  newLayer.set('id', layerConfig.id);
  newLayer.set('name', layerConfig.name);
  newLayer.set('type', layerConfig.geoType);
  if ('minZoom' in layerConfig && layerConfig.minZoom) {
    newLayer.setMinZoom(layerConfig.minZoom);
  }
  if ('maxZoom' in layerConfig && layerConfig.maxZoom) {
    newLayer.setMaxZoom(layerConfig.maxZoom);
  }
  map.value.addLayer(newLayer);
  loadedLayers.value[layerConfig.id] = newLayer;
}

const createLayer = (layer) => {
  return new Promise((resolve, reject) => {
    let newLayer;
    switch (layer.dataType) {
      case 'dataApi':
        getData(layer.id)
          .then(response => {
            const data = response.data || [];
            newLayer = createPointLayer({
              data: data,
              layerId: layer.id,
              layerType: layer.geoType
            });
            console.log(layer)
            resolve(newLayer);
          })
          .catch(error => {
            console.error(`获取图层 ${layer.id} 数据失败:`, error);
            reject(error);
          });
        break;
      default:
        console.error('未知图层类型:', layer.type);
        reject(new Error(`未知图层类型: ${layer.type}`));
        break;
    }
  });
}

const addLayer = (layer) => {
  createLayer(layer).then(newLayer => {
    removeLayer(layer.id);
    addLayerToMap(newLayer, layer);
  }).catch(error => {
    console.error('图层加载失败:', error);
  });
}

defineExpose({
  map
})

onMounted(() => {
  initMap()
  emitter.on('addLayer', (data) => {
    addLayer(data)
  })
  emitter.on('removeLayer', (layerid) => {
    removeLayer(layerid)
  })
})

onUnmounted(() => {
  emitter.off('addLayer')
})
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
}

/* 移动端优化 */
@media screen and (max-width: 768px) {
  .map-container {
    touch-action: manipulation; /* 优化触摸体验 */
  }
}
</style>